<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<?php
$arr = array("foo" => "bar", 12 => true);

echo $arr["foo"]; // bar
echo ',';
echo $arr[12];    // 1
echo ',';
echo count($arr);
echo ',';
?>

<?php

$arr = array("somearray" => array(6 => 5, 13 => 9, "a" => 42));

echo $arr["somearray"][6];    // 5
echo $arr["somearray"][13];   // 9
echo $arr["somearray"]["a"];  // 42
?>

<?php

// This array is the same as ...
$arr = array(5 => 43, 32, 56, "b" => 12);
foreach ($arr as $i => $value) {
  print($arr[$i] . ',' . $value . ',');
}
// ...this array
array(5 => 43, 6 => 32, 7 => 56, "b" => 12);

// 排序
$offsets = array(); //5 => 13, 8 => 12, 1 => 3, 13 => 16);
foreach ($offsets as $begin => $end) {
  echo "offset[" . $begin . "] = " . $end. "<br/>";
}

class ColorOffset {
  public $start = null;
  public $end = null;
  function __construct($s, $e) {
    $this->start = $s;
    $this->end = $e;
  }
}

function InsertOffset($offsets, $item) {
  $len = count($offsets);

  for($i = $len - 1; $i >= 0; --$i) {
    if ($item->start > $offsets[$i]->start) {
      $res = array_merge(array_slice($offsets, 0, $i + 1), array($item), array_slice($offsets, $i + 1));
      return $res;
    }
  }
  return array_merge(array($item), array_slice($offsets, 0));
}

# 添加元素
// array_push($offsets, new ColorOffset(6, 14));
// array_push($offsets, new ColorOffset(16, 19));
// array_push($offsets, new ColorOffset(3, 13));
function MergeColorOffset($offsets) {
  do {
    $do_merge = false;
    $index = 0;

    foreach($offsets as $co) {
      print 'index = ' . $index . '<br/>';
      if ($index > 0) {
        if ($co->start < $prev->end) {
          printf("%d %d unset an item ---------- <br/>", $co->start, $prev->end);
          if ($prev->end < $co->end) {
            $prev->end = $co->end;
            print "use current end : " . $co->end . "<br/>";
          }
          print count($offsets) . '=';
          unset($offsets[$index]);
          // ++$index;
          print count($offsets) . '=';
          $do_merge = true;
        }
      } else {
        $prev = $offsets[$index];
      }
      ++$index;
    }
  }while($do_merge);

  return $offsets;
}

$offsets = InsertOffset($offsets, new ColorOffset(6, 14));
$offsets = InsertOffset($offsets, new ColorOffset(6, 18));
$offsets = InsertOffset($offsets, new ColorOffset(126, 128));
$offsets = InsertOffset($offsets, new ColorOffset(26, 38));
$offsets = InsertOffset($offsets, new ColorOffset(16, 32));
$offsets = InsertOffset($offsets, new ColorOffset(17, 28));

print "<br/>before merge : <br/>";
foreach ($offsets as $co) {
  printf("start=%d, end=%d<br/>", $co->start, $co->end);
}

$offsets = MergeColorOffset($offsets);

print "after merge : <br/>";
foreach ($offsets as $co) {
  printf("start=%d, end=%d<br/>", $co->start, $co->end);
}

?>
